package com.woniu.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.woniu.Face.BaiduAIFace;
import com.woniu.SetingModel.Setingmodel;
import com.woniu.dao.*;

import com.woniu.pojo.*;
import com.woniu.pojo.User;
import com.woniu.pojo.UserExample;
import com.woniu.service.UserService;
import com.woniu.utils.EmailLogin;
import com.woniu.utils.MessageLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private UserroleDao userroleDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private LessonDao lessonDao;
    @Resource
    private SchoolDao schoolDao;
    @Resource
    private RolepermissionDao rolepermissionDao;
    @Resource
    private PermissionDao permissionDao;
    @Autowired
    BaiduAIFace faceapi;
    @Autowired
    Setingmodel setingmodel;
    //修改密码
    @Override
    public Boolean changePwd(User user, String pwd1, String pwd2) {
        if (!pwd1.equals(pwd2)) {
            return false;
        }
        user.setUpwd(pwd1);
        userDao.updateByPrimaryKeySelective(user);
        return true;
    }

    //更新用户信息
    @Override
    public void updatePersonalMassage(User user, HttpSession session) {
        userDao.updateByPrimaryKeySelective(user);
        session.setAttribute("user", user);
    }
    //查找用户的状态
    @Override
    public void findUstate(User user) {
        LessonExample lessonExample = new LessonExample();
        lessonExample.createCriteria().andNameEqualTo(user.getUname());
        List<Lesson> lessonList = lessonDao.selectByExample(lessonExample);
        if (lessonList.size() != 0) {
            user.setUstate("有课");
        } else {
            user.setUstate("休息");
        }
        userDao.updateByPrimaryKeySelective(user);
    }
    //查找所有的地区
    @Override
    public List<School> findAllArea() {
        return schoolDao.selectByExample(null);
    }
    //人脸识别
    @Override
    public Map<String, Object> searchface(StringBuffer imagebase64) {
        Map map =null;
        try {
            String substring = imagebase64.substring(imagebase64.indexOf(",") + 1, imagebase64.length());
            setingmodel.setImgpath(substring);
            setingmodel.setGroupID("woniu_boss");
            System.out.println(substring);
            map = faceapi.FaceSearch(setingmodel);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 加班所需要的用户信息集合
     *
     * @return
     */
    @Override
    public List<User> findAll4workselect() {
        List<User> userList = userDao.selectByExample(null);
//        if (userList==null){
//            userList
//        }
        return userList;
    }

    @Override
    public User findOne(Integer uid) {
        return userDao.selectByPrimaryKey(uid);
    }

    //按账号来查找用户角色
    @Override
    public Set<String> findUserRoles(Integer uid) {
        Set<String> set=new HashSet<>();
        UserroleExample userroleExample=new UserroleExample();
        userroleExample.createCriteria().andUidEqualTo(uid);
        List<Userrole> userroleList = userroleDao.selectByExample(userroleExample);
        List<Integer> ridList=new ArrayList<>();
        for (Userrole userrole : userroleList) {
            ridList.add(userrole.getRid());
        }
        RoleExample roleExample=new RoleExample();
        roleExample.createCriteria().andRidIn(ridList);
        List<Role> roleList = roleDao.selectByExample(roleExample);

        for (Role role : roleList) {
            set.add(role.getRname());
        }
        return set;
    }
    //按账号来查找用户权限
    @Override
    public Set<String> findUserPermission(Integer uid) {
        Set<String> set=new HashSet<>();

        UserroleExample userroleExample=new UserroleExample();
        userroleExample.createCriteria().andUidEqualTo(uid);
        List<Userrole> userroleList = userroleDao.selectByExample(userroleExample);

        List<Integer> ridList=new ArrayList<>();

        for (Userrole userrole : userroleList) {
            ridList.add(userrole.getRid());
        }

        RolepermissionExample rolepermissionExample=new RolepermissionExample();
        rolepermissionExample.createCriteria().andRidIn(ridList);
        List<Rolepermission> rolepermissions = rolepermissionDao.selectByExample(rolepermissionExample);

        List<Integer> pidList = new ArrayList<>();

        for (Rolepermission rolepermission : rolepermissions) {
            pidList.add(rolepermission.getPid());
        }


        PermissionExample permissionExample=new PermissionExample();
        permissionExample.createCriteria().andPidIn(pidList);
        List<Permission> permissionList = permissionDao.selectByExample(permissionExample);

        for (Permission permission : permissionList) {
            set.add(permission.getUrl());
        }

        return set;

    }
    //按手机号查找用户
    @Override
    public User findOneByUphone(String uPhone) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUphoneEqualTo(uPhone);
        return userDao.selectByExample(userExample).size()==0?null:userDao.selectByExample(userExample).get(0);
    }

    @Override
    public void resertPwd(String uphone) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUphoneEqualTo(uphone);
        List<User> userList = userDao.selectByExample(userExample);
        User user = userList.get(0);
        user.setUpwd("e10adc3949ba59abbe56e057f20f883e");
         userDao.updateByPrimaryKeySelective(user);
    }
//按用户账号和手机号查找
    @Override
    public User findOneByUaccount(String username) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUaccountEqualTo(username);
        List<User> userList = userDao.selectByExample(userExample);
        if (userList.size()==0){
            UserExample userExample1=new UserExample();
            userExample1.createCriteria().andUphoneEqualTo(username);
            userList = userDao.selectByExample(userExample1);
        }
        return userList.size() == 0 ? null : userList.get(0);
    }
//发送短信
    @Override
    public String login(String phone, Integer code1) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUphoneEqualTo(phone);
        List<User> userList = userDao.selectByExample(userExample);
        if (userList != null) {
            try {
                String code = Integer.toString(code1);
                SendSmsResponse sendSms = MessageLogin.sendSms(phone, code);//填写你需要测试的手机号码
                System.out.println("短信接口返回的数据----------------");
                System.out.println("Code=" + sendSms.getCode());
                System.out.println("Message=" + sendSms.getMessage());
                System.out.println("RequestId=" + sendSms.getRequestId());
                System.out.println("BizId=" + sendSms.getBizId());
            } catch (Exception e) {
                return "短信发送失败";
            }
        }else{
            return "该用户不存在";
        }
        return "发送成功";
    }


    /**
     * userrole找讲师
     * @return
     */
    @Override
    public List<User> findTeacher() {
        UserroleExample userroleExample=new UserroleExample();
        userroleExample.createCriteria().andRidEqualTo(3);
        List<Userrole> userroleList=userroleDao.selectByExample(userroleExample);

        List<Integer> uids=new ArrayList<>();
        for (Userrole userroles: userroleList) {
           uids.add(userroles.getUid());
        }
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUidIn(uids);
        List<User> userList=userDao.selectByExample(userExample);
        return userList;
    }

    /**
     * 查看所有的角色
     * @return
     */
    @Override
    public List<Role> findAllRole() {

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andSoftdelNotEqualTo("0");
        return roleDao.selectByExample(roleExample);
    }

    @Override
    public String EmailLogin(String email,HttpSession session) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        List<User> userList = userDao.selectByExample(userExample);
        if (userList.size()==0){
            return "该邮箱尚未注册";
        }
        EmailLogin emailLogin=new EmailLogin();
        String code = emailLogin.achieveCode();
        EmailLogin.sendAuthCodeEmail(email, code);
        session.setAttribute("emailCode", code);
        return "验证码发送成功";

    }

    @Override
    public User findOneByEmail(String email) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        List<User> userList = userDao.selectByExample(userExample);
        return userList.size()==0?null: userList.get(0);
    }

    @Override
    public User findOneByfaceid(String faceid) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andFaceidEqualTo(faceid);
        List<User> userList = userDao.selectByExample(userExample);
        return userList.size()==0?null: userList.get(0);
    }

    /**
     * 增加一个角色
     * @param rname
     * @return
     */
    @Override
    public int addRole(String rname) {
        //根据ranme判断角色是否存在
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andRnameEqualTo(rname);
        List<Role> roles = roleDao.selectByExample(roleExample);
        if(roles.size()>0){return -1;}
        //增加角色
        Role role = new Role();
        role.setRname(rname);
        role.setSoftdel("1");
        roleDao.insertSelective(role);
        //增加默认主页面
        //1获取rid
        RoleExample roleExample2 = new RoleExample();
        roleExample2.createCriteria().andRnameEqualTo(rname);
        List<Role> roles1 = roleDao.selectByExample(roleExample2);
        //2增加主页面
        Rolepermission rolepermission = new Rolepermission();
        rolepermission.setRid(roles1.get(0).getRid());
        rolepermission.setPid(1);
        rolepermissionDao.insertSelective(rolepermission);
        //3添加首页的主页
        Rolepermission rolepermission1 = new Rolepermission();
        rolepermission1.setRid(roles1.get(0).getRid());
        rolepermission1.setPid(20);
        return rolepermissionDao.insertSelective(rolepermission1);
    }
    /**
     * 分页展示用户信息
     * @param pageBean
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> findByPage(PageBean pageBean, User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(user.getArea() != null && !user.getArea().equals("")){
            criteria.andAreaEqualTo(user.getArea());
        }
        if(user.getUname() != null && !user.getUname().equals("")){
            criteria.andUnameLike("%"+user.getUname()+"%");
        }
        if(user.getUaccount() != null && !user.getUaccount().equals("")){
            criteria.andUaccountEqualTo(user.getUaccount());
        }
        //分页查询
        long countRow= userDao.countByExample(userExample);
        pageBean.setCountRow((int)countRow);
        Integer countPage=pageBean.getCountRow()%pageBean.getPageSize()==0?pageBean.getCountRow()/pageBean.getPageSize():pageBean.getCountRow()/pageBean.getPageSize()+1;
        pageBean.setCountPage(countPage);
        userExample.setOffset((long)((pageBean.getCurrentPage()-1)*pageBean.getPageSize()));
        userExample.setLimit(pageBean.getPageSize());
        //倒叙查找（新加用户可以显示在前面）
        userExample.setOrderByClause("uid DESC");

        List<User> userList = userDao.selectByExample(userExample);
        Map<String, Object> map = new HashMap<>();
        map.put("userList",userList);
//        List<Userrole> userList2 = new ArrayList<>();
//        for (int i = 0;i<userList.size();i++){
//            userList2 = userList.get(i).getUserroleList();
//        }
        map.put("pageBean",pageBean);
        return map;
    }

    /**
     * 改变一个用户的锁定状态
     * @param uid
     * @return
     */
    @Override
    public int changesoftdel(Integer uid) {
        //根据uid查看原有的状态
        User user = userDao.selectByPrimaryKey(uid);
        User user1 = new User();
        user1.setUid(uid);
        if(user.getSoftdel().equals("0")){
            user1.setSoftdel("1");
        }else {
            user1.setSoftdel("0");
        }
        return  userDao.updateByPrimaryKeySelective(user1);
    }

    /**
     * 批量改变用户的锁定状态
     * @param uid
     * @return
     */
    @Override
    public int changesoftdelmany(Integer[] uid) {
        //通过rid获取uid
        UserroleExample userroleExample = new UserroleExample();
        userroleExample.createCriteria().andRidEqualTo(4);
        List<Userrole> userroles = userroleDao.selectByExample(userroleExample);

        List<Integer> uidList = new ArrayList<>();
        for(int i = 0 ;i<userroles.size();i++){
            uidList.add(userroles.get(i).getUid());
        }
        List<Integer> uidList2 = new ArrayList<>();
        int account = 0;
        for(int i = 0 ;i<uid.length;i++){
            if(!(uidList.contains(uid[i]))){
                uidList2.add(uid[i]);
            }else {
                account++;
            }
        }
        if(account == uid.length){return -1;}
        for(int i = 0;i<uidList2.size();i++){
            int changesoftdel = changesoftdel(uidList2.get(i));
           //中间过程失败，直接返回-1
            if(!(changesoftdel>0)){
                return -1;
            }
        }
        return 1;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public int saveone(User user,String rid) {
        //通过填写的用户账号,判断这个用户账户是否存在
        UserExample userExample1 = new UserExample();
        userExample1.createCriteria().andUaccountEqualTo(user.getUaccount());
        List<User> userList1 = userDao.selectByExample(userExample1);
        if(userList1.size()>0){
            //如果存在直接返回-1
            return -1;
        }
        //不存在这个账户在增加用户(默认密码123456)
        user.setUpwd("e10adc3949ba59abbe56e057f20f883e");
        userDao.insertSelective(user);
        //获取新增加这个用户的uid
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUaccountEqualTo(user.getUaccount());
        List<User> userList = userDao.selectByExample(userExample);
        //增加用户角色
        Userrole userrole = new Userrole();
        userrole.setUid(userList.get(0).getUid());
        if(rid == null && !rid.equals("")){
            //如果为空默认添加的角色为老师
            userrole.setRid(1);
        }else {
            userrole.setRid(Integer.parseInt(rid));
        }
        return userroleDao.insertSelective(userrole);
    }

    /**
     * 通过主键查询用户信息
     * @param uid
     * @return
     */
    @Override
    public User selectByuid(Integer uid) {
       return userDao.selectByPrimaryKey(uid);
    }

    /**
     * 查询用户的所有状态（不重复）
     * @return
     */
    @Override
    public List<String> selectustate() {
        List<User> userList = userDao.selectByExample(null);
        List<String> stateList = new ArrayList<>();
        for(int i = 0;i<userList.size();i++){
            if(stateList.size() == 0){
                stateList.add(userList.get(i).getUstate());
            }else if(!(stateList.contains(userList.get(i).getUstate()))){
                stateList.add(userList.get(i).getUstate());
            }
        }
        return stateList;
    }

    /**
     * 修改当前用户
     * @param user
     * @return
     */
    @Override
    public int updateone(User user) {
        //修改用户名校核
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUidNotEqualTo(user.getUid());
        criteria.andUaccountEqualTo(user.getUaccount());
        List<User> userList = userDao.selectByExample(userExample);
        if(userList.size()>0){return -1;}
        return userDao.updateByPrimaryKeySelective(user);
    }

    /**
     * 查看当前用户有和 没有的角色（登录用户不是管理员不展示管理员角色）
     * @param uid
     * @return
     */
    @Override
    public Map<String, Object> roleshow(Integer uid) {
        //一获取 uid 对应的权限
        //1用过uid获取rid
        UserroleExample userroleExample = new UserroleExample();
        userroleExample.createCriteria().andUidEqualTo(uid);
        List<Userrole> userroles = userroleDao.selectByExample(userroleExample);
        List<Integer> ridList = new ArrayList<>();
        for(int i = 0;i<userroles.size();i++){
            ridList.add(userroles.get(i).getRid());
        }
        //通过rids 获取role对象
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andRidIn(ridList);
        //获取当前登录的账户信息（判断是不是管理员）
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole("管理员")){
            criteria.andRidNotEqualTo(4);
        }
        List<Role> roles = roleDao.selectByExample(roleExample);

        //获取没有的role对象
        RoleExample roleExample2 = new RoleExample();
        RoleExample.Criteria criteria1 = roleExample2.createCriteria();
        criteria1.andRidNotIn(ridList);
        if(!subject.hasRole("管理员")){
            criteria1.andRidNotEqualTo(4);
        }
        List<Role> roles2 = roleDao.selectByExample(roleExample2);
        Map<String, Object> map = new HashMap<>();
        map.put("assignpermissionList",roles);
        map.put("unassignperissionList",roles2);
        return map;
    }


    /**
     * 增加角色
     * @param uid
     * @param rid
     * @return
     */
    @Override
    public int saverole(Integer uid, Integer rid) {
        Userrole userrole = new Userrole();
        userrole.setUid(uid);
        userrole.setRid(rid);
        return userroleDao.insertSelective(userrole);
    }

    /**
     * 删除角色
     * @param rid
     * @param uid
     * @return
     */
    @Override
    public int deleterole(Integer uid, Integer rid) {

        //根据uid 判断这个用户还剩余多少角色，假如只剩余一个不能删除，必须保证要有一个角色
        UserroleExample userroleExample1 = new UserroleExample();
        userroleExample1.createCriteria().andUidEqualTo(uid);
        List<Userrole> userroles = userroleDao.selectByExample(userroleExample1);
        if(userroles.size() == 1){
            //不能删除
            return -1;
        }
        UserroleExample userroleExample = new UserroleExample();
        UserroleExample.Criteria criteria = userroleExample.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andRidEqualTo(rid);
        return userroleDao.deleteByExample(userroleExample);
    }

    /**
     * 增加权限
     * @param
     * @param pid
     * @return
     */
    @Override
    public int savepermission(Integer rid, Integer pid) {
        //通过pid查父节点
        Permission permission = permissionDao.selectByPrimaryKey(pid);
        int parent = permission.getParentid();
        //判断这个父节点权限有无
        RolepermissionExample rolepermissionExample = new RolepermissionExample();
        RolepermissionExample.Criteria criteria = rolepermissionExample.createCriteria();
        criteria.andPidEqualTo(parent);
        criteria.andRidEqualTo(rid);
        List<Rolepermission> rolepermissions = rolepermissionDao.selectByExample(rolepermissionExample);
        //加父节点
        if(rolepermissions.size() == 0){
            Rolepermission rolepermission2 = new Rolepermission();
            rolepermission2.setRid(rid);
            rolepermission2.setPid(parent);
            rolepermissionDao.insertSelective(rolepermission2);
        }
        //将rid 和 pid 持久化
        Rolepermission rolepermission = new Rolepermission();
        rolepermission.setRid(rid);
        rolepermission.setPid(pid);
        return rolepermissionDao.insertSelective(rolepermission);
    }

    /**
     * 角色收回权限
     * @param rid
     * @param pid
     * @return
     */
    @Override
    public int deletepermission(Integer rid, Integer pid) {
        //不能删除首页判断
        if(pid == 1){
            return -2;
        }
        //通过pid查父节点
        Permission permission = permissionDao.selectByPrimaryKey(pid);
        int parent = permission.getParentid();
        //通过rid查找所有的pid
        RolepermissionExample rolepermissionExample = new RolepermissionExample();
        RolepermissionExample.Criteria criteria = rolepermissionExample.createCriteria();
        criteria.andRidEqualTo(rid);
        criteria.andPidNotEqualTo(parent);
//        criteria.andPidEqualTo(parent);
        List<Rolepermission> rolepermissions = rolepermissionDao.selectByExample(rolepermissionExample);

        for(int i = 0;i<rolepermissions.size();i++){
            //通过parent 和 pidList 查所有父节点
            int pid2 = rolepermissions.get(i).getPid();
            PermissionExample permissionExample = new PermissionExample();
            PermissionExample.Criteria criteria1 = permissionExample.createCriteria();
            criteria1.andPidEqualTo(pid2);
            criteria1.andParentidEqualTo(parent);
            List<Permission> permissionList = permissionDao.selectByExample(permissionExample);
            if(permissionList.size()>0 && pid2!=pid){
                //只删除传来的rid \  pid
                RolepermissionExample rolepermissionExample3 = new RolepermissionExample();
                RolepermissionExample.Criteria criteria3 = rolepermissionExample3.createCriteria();
                criteria3.andPidEqualTo(pid);
                criteria3.andRidEqualTo(rid);
                return rolepermissionDao.deleteByExample(rolepermissionExample3);
            }
        }
        //删除传来的rid \  pid   及 rid \ parent
        RolepermissionExample rolepermissionExample4 = new RolepermissionExample();
        RolepermissionExample.Criteria criteria4 = rolepermissionExample4.createCriteria();
        criteria4.andRidEqualTo(rid);
        criteria4.andPidEqualTo(pid);
        rolepermissionDao.deleteByExample(rolepermissionExample4);

        RolepermissionExample rolepermissionExample5 = new RolepermissionExample();
        RolepermissionExample.Criteria criteria5 = rolepermissionExample5.createCriteria();
        criteria5.andRidEqualTo(rid);
        criteria5.andPidEqualTo(parent);
        return rolepermissionDao.deleteByExample(rolepermissionExample5);
    }


    @Override
    public List<User> findAllUser() {
        List<Userrole> userroleList = userroleDao.selectByExample(null);
        List<Integer> uidList = new ArrayList<>();
        for (Userrole userrole : userroleList) {
            Role role = new Role();
            role = roleDao.selectByPrimaryKey(userrole.getRid());

            if (role.getRname().equals("班主任")) {
                uidList.add(userrole.getUid());
            }
        }
        UserExample userExample = new UserExample();
        UserExample.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andUidIn(uidList);
        return userDao.selectByExample(userExample);
    }

    @Override
    public Boolean codeVerification(HttpSession session, String code) {
        //判断验证码是否正确
        String randStr = session.getAttribute("randStr").toString();
        System.out.println(randStr);
        if (!code.equals(randStr)) {
            return false;
        }
        return true;

    }

    @Override
    public User login(User user) {
        return null;
    }
}
